#include<linux/in.h>  
#include<linux/inet.h>  
#include<linux/socket.h>  
#include<net/sock.h>  
  
#include<linux/init.h>  
#include<linux/module.h>  

#define BUFFSIZE 1024

void jiang_debug( void )
{
    printk("just debug");
}

int myserver(void)
{  
  
    struct socket *sock,*client_sock;  
    struct sockaddr_in s_addr;  
    unsigned short portnum=8888;  
    int ret=0;  

    memset(&s_addr,0,sizeof(s_addr));  
    s_addr.sin_family=AF_INET;  
    s_addr.sin_port=htons(portnum);  
    s_addr.sin_addr.s_addr=in_aton("127.0.0.1");  


    sock=(struct socket *)kmalloc(sizeof(struct socket),GFP_KERNEL);  

    /*create a socket*/  
    ret=sock_create_kern(&init_net, AF_INET,SOCK_STREAM, IPPROTO_TCP,&sock);  
    if(ret){  
            printk("server:socket_create error!\n");  
    }  
    printk("server:socket_create ok!\n");  

    /*bind the socket*/  
    ret=kernel_bind(sock,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in));  
    if(ret<0){  
            printk("server: bind error\n");  
            return ret;  
    }  
    printk("server:bind ok!\n");  

    /*listen*/  
    ret=kernel_listen(sock,10);  
    if(ret<0){  
            printk("server: listen error\n");  
            return ret;  
    }  
    printk("server:listen ok!\n");  

    ret=kernel_accept(sock,&client_sock,10);
    if(ret<0){  
            printk("server:accept error!\n");  
            return ret;  
    }  

    printk("server: accept ok, Connection Established\n");  

    /*kmalloc a receive buffer*/  
    char *recvbuf=NULL;  
    recvbuf=kmalloc(1024,GFP_KERNEL);  
    if(recvbuf==NULL){  
            printk("server: recvbuf kmalloc error!\n");  
            return -1;  
    }  
    memset(recvbuf, 0, 1024);  

    /*receive message from client*/  
    struct kvec vec;  
    struct msghdr msg;  
    memset(&vec,0,sizeof(vec));  
    memset(&msg,0,sizeof(msg));  
    vec.iov_base=recvbuf;  
    vec.iov_len=1024;  
    msg.msg_flags=MSG_NOSIGNAL;
    msleep(1000);
    jiang_debug();
    ret=kernel_recvmsg(client_sock,&msg,&vec,1,1024, msg.msg_flags); /*receive message*/  
    recvbuf[1023] = 0;
    printk("receive message:\n %s\n",recvbuf);  
          
    /*release socket*/  
    printk("release socket now\n");
    sock_release(client_sock);  
    sock_release(sock);  
    return ret;  
}  
  
static int server_init(void){  
    printk("server init:\n");  
    return (myserver());  
}  
  
static void server_exit(void){  
    printk("good bye\n");  
}  
  
module_init(server_init);  
module_exit(server_exit);  
  
MODULE_LICENSE("GPL");
